if !SERVER then return end
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )

ENT.FlightSound = ""

ENT.AsteroidList = {}
					
ENT.AsteroidList[5] =	{
					 "models/asteroid5.mdl"
					}

ENT.AsteroidList[4] =	{
					 "models/asteroid4.mdl"					 
					}

ENT.AsteroidList[3] =	{
					 "models/asteroid3.mdl"
					}					

ENT.AsteroidList[2] =	{
			 	     "models/asteroid2.mdl"
					}										

ENT.AsteroidList[1] =	{
					 "models/asteroid1.mdl"
					}										
				

ENT.AsteroidPieces = {}
ENT.AsteroidPieces[5] = { "1,1,1,1,1", "1,1,1,2", "1,1,3", "1,4", "2,3", "2,2,1" }
ENT.AsteroidPieces[4] = { "1,1,1,1", "1,1,2", "1,3", "2,2"}
ENT.AsteroidPieces[3] = { "1,1,1", "1,2"}
ENT.AsteroidPieces[2] = { "1,1"}

					
function ENT:Initialize()

	local rndSize = math.random(3,5)
	self.size = rndSize
	self:SetModel( self.AsteroidList[rndSize][math.random(1,table.Count(self.AsteroidList[rndSize]))])
	self:SetSolid( SOLID_VPHYSICS )
	self:SetCollisionGroup( COLLISION_GROUP_NONE)
	self:PhysicsInit( SOLID_VPHYSICS )
	
	self:SetAngles( Angle(math.random(1,360),math.random(1,360),math.random(1,360) ) )
	
	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
		phys:SetMass(50000)
		phys:SetMaterial("boulder")
		phys:EnableGravity(false)
		phys:AddAngleVelocity(Angle(math.random(-360,360),math.random(-360,360),math.random(-360,360) ))
	end
	self.Created = CurTime()
end

function ENT:Think()
	
	
	self:GetPhysicsObject():AddVelocity(self:GetVelocity():Angle():Forward() * 25)
	
	if self:GetVelocity():Length() > 3000 then
		self:GetPhysicsObject():SetVelocity(self:GetVelocity():Angle():Forward() * 3000)
	end
	
	local isShips = ents.FindByClass("as_ship")
	
	if table.Count(isShips) > 0 then
		self:GetPhysicsObject():AddVelocity((isShips[math.random(1,table.Count(isShips))]:GetPos() - self:GetPos()):Angle():Forward() * 75)
	end
	
	self:NextThink( CurTime() + 1)

end

function ENT:PhysicsCollide( data, physobj )

	if !(data.HitEntity:GetClass() == "laser_shot" or data.HitEntity:GetClass() == "as_ship") then return end
	
	if data.DeltaTime >= 0.9 then
		WorldSound("Boulder.ImpactHard",data.HitPos, 228, 120)
		if ValidEntity(data.HitEntity.owner) then
			WorldSound("Boulder.ImpactHard",data.HitEntity.owner:GetPos(), 228, 120)
		end
		if ValidEntity(data.HitEntity.owner) and
		   !(data.HitEntity:GetClass() == "as_ship") then
			data.HitEntity.owner.score = data.HitEntity.owner.score + ( ASTEROID_POINTS / self.size)
			if (data.HitEntity.owner.score / EXTRA_LIFE_SCORE) >= data.HitEntity.owner.extraLives then
				data.HitEntity.owner.extraLives = data.HitEntity.owner.extraLives + 1
				data.HitEntity.owner.lives = data.HitEntity.owner.lives + 1
				if data.HitEntity.owner.lives > MAX_LIVES then
					data.HitEntity.owner.lives = MAX_LIVES
				end
				umsg.Start("updateLives", data.HitEntity.owner)
					umsg.Long(data.HitEntity.owner.lives)
				umsg.End()
			end
			data.HitEntity.owner:SetFrags(data.HitEntity.owner.score)
			umsg.Start("updateScore", data.HitEntity.owner)
				umsg.Long(data.HitEntity.owner.score)
			umsg.End()
		end
		self:Fragment( self:GetVelocity() )
	end
	
end

function ENT:Fragment( newVel )

	print("Fragmenting " .. tostring(self))
	if self.fragged then return end
	self.fragged = true
	
	local szPieces = {}

	self:EmitSound("Breakable.Concrete", 250, 200)	
	
	local effData = EffectData()
	effData:SetOrigin(self:GetPos())
	effData:SetScale(self:BoundingRadius() * 1000)
	effData:SetMagnitude(self:BoundingRadius() * 1000)
	util.Effect("Explosion", effData)
	
	if self.size > 1 then

		local fragPos = self:GetPos()
		local fragVel = self:GetVelocity()

		szPieces = string.Explode(",", self.AsteroidPieces[self.size][math.random(1,table.Count(self.AsteroidPieces[self.size]))])
		for k, v in pairs(szPieces) do
			local fragment = ents.Create("asteroid")
			fragment:SetPos(fragPos)
			fragment:Spawn()
			fragment:SetCollisionGroup(COLLISION_GROUP_INTERACTIVE_DEBRIS)
			timer.Simple(1, 
							function(fragment) 
								if ValidEntity(fragment) then 
									fragment:SetCollisionGroup(COLLISION_GROUP_NONE) 
								end 
							end )
			fragment.size = tonumber(v)
			fragment:ChangeSize()
			local rndDir = Vector(math.Rand(-1,1),math.Rand(-1,1), math.Rand(-1,1))
			fragment:GetPhysicsObject():SetVelocity( (rndDir * fragVel:Length()) * 2.25 )
		end
		self:Remove()
	else
		self:Remove()
	end
	

end

function ENT:ChangeSize()

	self.Entity:SetModel( self.AsteroidList[self.size][math.random(1,table.Count(self.AsteroidList[self.size]))])

end

function ENT:Shoot( targPos, startPos, vel )
	
	local sPhys = self:GetPhysicsObject()
	local velDir = (targPos - startPos):GetNormal()
	self:SetAngles(self:AlignAngles(self:GetUp():Angle(),  velDir:Angle()))
	sPhys:SetVelocity(velDir * vel)
	
end
